var Feeds = [];
var FeedsLoaded = false;

var FeedViewerUrl = chrome.extension.getURL('feed_viewer.html');
var FeedTags = [ 'rss', 'feed' ];

function isFeed()
{
    for(var t in FeedTags)
    {
        var el = document.getElementsByTagName(FeedTags[t])[0];
        
        if (el)
        {
            var parent = el.parentElement;
            
            if(!parent || parent.tagName.toUpper() == 'BODY')
            {
                return true;            
            }
        }
    }
    
    return false;
}


function findFeeds() 
{
    if (!FeedsLoaded)
    {
        FeedsLoaded = true;
    
        var item;
        var result = document.evaluate(
            '//link[@rel="alternate"][' +
            'contains(@type, "rss") or ' +
            'contains(@type, "atom") or ' +
            'contains(@type, "rdf")]',
            document, null, 0, null);
        
        while (item = result.iterateNext())
        {
            Feeds.push(item.href);
        }

        if (Feeds.length > 0)
        {
            chrome.extension.connect().postMessage(
            {
                action: 'FeedsDiscovered',
                data: Feeds
            });
        }
    }
}

if (window == top) 
{
    if (isFeed())
    {
        window.location.replace(FeedViewerUrl + 
                                '?' + window.location.href + 
                                '#' + encodeURIComponent(document.title));
    }
    else
    {
        findFeeds();
        window.addEventListener("focus", findFeeds);

        chrome.extension.onConnect.addListener(function(port)
        {
            port.onMessage.addListener(function(msg)
            {
                if (msg == 'GetFeeds')
                {
                    port.postMessage(Feeds);
                }
            });
        });
    }
}
else
{
    if (window.location.href.indexOf('http://www.google.com/reader/lite/feed/') > -1)
    {
	    document.getElementById('news-tab').style.display='None';
	    document.getElementById('popular-tab').style.display='None';
	    document.getElementById('sports-tab').style.display='None';
    }
}